import imp
from threading import Thread, Lock

THREAD_LOMIT = 5

class TPool:
  def __init__(self):
    # self.limit = THREAD_LOMIT
    self.lock = Lock()
    self.pool = []
    self.task_seq = []
    self.params_seq = []

  def _add(self, task, param):
    self.task_seq.append(task)
    self.params_seq.append(param)
    self._deal()
    

  def _deal(self):
    # clear finished
    # alive_t = []
    # for t in self.pool:
    #   if t.is_alive():
    #     alive_t.append(t)
    # self.pool = alive_t

    # new task
    if len(self.pool) < THREAD_LOMIT and len(self.task_seq) > 0:
      task = self.task_seq[0]
      param = self.params_seq[0]
      def to_do(*args):
        task(*args)
        self._deal()
      self.task_seq.pop(0)
      self.params_seq.pop(0)
      t = Thread(target=to_do, args=param)
      self.pool.append(t)
      t.start()

  def res(self):
    res = []
    alive_t = []
    for t in self.pool:
      if t.is_alive():
        alive_t.append(t)
      else:
        res.append(t.get_result())
    self.pool = alive_t
    self._deal()